//
//  WHScanViewController.m
//  WHEasyBizLink
//
//  Created by shengmeng chen on 2024/11/26.
//

#import "WHScanViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "WHScanView.h"
#import "WHScanWithImgView.h"
#import "WHDialog.h"
#import "WHPreviewImageVC.h"

@interface WHScanViewController ()<AVCapturePhotoCaptureDelegate>
/** 会话对象 */
@property (nonatomic, strong) AVCaptureSession *session;
/** 图层类 */
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;
@property (nonatomic, strong) WHScanWithImgView *scanningView;
@property (nonatomic,strong)AVCapturePhotoOutput *captureOutput;
//拍照图片数组
@property (nonatomic, copy) NSMutableArray<UIImage *> *imgArray;
@end

@implementation WHScanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"扫一扫";
    self.view.backgroundColor = [UIColor blackColor];
    [self setupScanningImage];
    
    // 创建扫描边框
    self.scanningView = [[WHScanWithImgView alloc] initWithFrame:self.view.frame outsideViewLayer:self.view.layer];
    [self.view addSubview:self.scanningView];
    __weak __typeof(self) weakSelf = self;
    self.scanningView.clicBtnBlock = ^(UIButton * _Nonnull btn) {
        [weakSelf Captureimage];
    };
    self.scanningView.imgPreviewBlock = ^{
        if (weakSelf.imgArray.count) {
            WHPreviewImageVC*vc =[WHPreviewImageVC new];
            vc.imgArray =weakSelf.imgArray;
            [weakSelf.navigationController pushViewController:vc animated:YES];
            vc.delateRefleshBlock = ^{
                UIImage *img = weakSelf.imgArray.lastObject;
                [weakSelf.scanningView setMImgPreviewImg:img num:(int)weakSelf.imgArray.count];
            };
        }
    };
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.scanningView  addTimer];
}
//页面消失，进入后台不显示该页面，关闭定时器
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear: animated];
    //关闭定时器
    [self.scanningView removeTimer];
}

#pragma mark - - - 二维码扫描
//- (void)setupScanningQRCode {
//    // 1、 获取摄像设备
//    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//    
//    // 2、 创建输入流
//    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
//    
//    // 3、 创建输出流
//    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
//    self.captureOutput = output;
//    // 4、设置代理 在主线程里刷新
//    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
//    
//    // 设置扫描范围(每一个取值0～1，以屏幕右上角为坐标原点)
//    output.rectOfInterest = CGRectMake(0.15, 0.24, 0.7, 0.52);
//    
//    // 5、 初始化链接对象（会话对象）
//    self.session = [[AVCaptureSession alloc] init];
//    //高质量采集率
//    [_session setSessionPreset:AVCaptureSessionPresetHigh];
//    
//    // 5.1 添加会话输入
//    [_session addInput:input];
//    
//    // 5.2 添加会话输出
//    [_session addOutput:output];
//    
//    // 6、设置输出数据类型，需要将元数据输出添加到会话后，才能指定元数据类型，否则会报错
//    // 设置扫码支持的编码格式(如下设置条形码和二维码兼容)
//    output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode, AVMetadataObjectTypeEAN13Code,  AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
//    
//    // 7、实例化预览图层, 传递_session是为了告诉图层将来显示什么内容
//    self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
//    _previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
//    _previewLayer.frame = self.view.layer.bounds;
//    
//    // 8、将图层插入当前视图
//    [self.view.layer insertSublayer:_previewLayer atIndex:0];
//    
//    // 9、启动会话
//    [_session startRunning];
//
//}

//- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
//    // 会频繁的扫描，调用代理方法
//    // 1. 如果扫描完成，停止会话
//    [self.session stopRunning];
//    // 2. 删除预览图层
//    [self.previewLayer removeFromSuperlayer];
//    
//    // 3. 设置界面显示扫描结果
//    if (metadataObjects.count > 0) {
//        AVMetadataMachineReadableCodeObject *obj = metadataObjects[0];
//            if ([obj.stringValue hasPrefix:@"http"]) {
//                // 提示：如果需要对url或者名片等信息进行扫描，可以在此进行扩展！
//                NSLog(@"扫描网址为----------%@", obj.stringValue);
//            } else { // 扫描结果为条形码
//                NSLog(@"扫描条形码为----------%@", obj.stringValue);
//            }
//        
//    }
//}

- (void)setupScanningImage
{
    //1.创建会话层
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        
    // Input
    AVCaptureDeviceInput*input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
        
    // Output
    self.captureOutput = [[AVCapturePhotoOutput alloc] init];
    NSDictionary *setDic = @{AVVideoCodecKey:AVVideoCodecTypeJPEG};
    AVCapturePhotoSettings* outputSettings = [AVCapturePhotoSettings photoSettingsWithFormat:setDic];
    
     [self.captureOutput setPhotoSettingsForSceneMonitoring:outputSettings];
        
        // Session
        self.session = [[AVCaptureSession alloc]init];
        //AVCaptureSessionPresetHigh:实现高质量的视频和音频输出
        [self.session setSessionPreset:AVCaptureSessionPresetHigh];
        // addInput:可称为虽然会话正在运行
        if ([self.session canAddInput:input])
        {
            [self.session addInput:input];
        }
        
        if ([self.session canAddOutput:_captureOutput])
        {
            [self.session addOutput:_captureOutput];
        }
        
    self.previewLayer =[AVCaptureVideoPreviewLayer layerWithSession:self.session];
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    self.previewLayer.frame = self.view.bounds;
    [self.view.layer insertSublayer:self.previewLayer atIndex:0];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if (self.session) {
               [self.session startRunning];
           }
    });
}

-(void)Captureimage
{
    // 设置照片方向
       AVCaptureConnection *connection = [self.captureOutput connectionWithMediaType:AVMediaTypeVideo];
       if (connection.supportsVideoOrientation) {
           connection.videoOrientation = self.previewLayer.connection.videoOrientation;
       }
       // 创建 AVCapturePhotoSettings
       AVCapturePhotoSettings *photoSettings = [AVCapturePhotoSettings photoSettings];
    if ([self.captureOutput.availablePhotoCodecTypes containsObject:AVVideoCodecTypeJPEG]) {
        NSDictionary *format = @{AVVideoCodecKey: AVVideoCodecTypeJPEG};
           photoSettings = [AVCapturePhotoSettings photoSettingsWithFormat:format];
       }
       // 防抖
       photoSettings.photoQualityPrioritization = YES;
       // 拍照
       [self.captureOutput capturePhotoWithSettings:photoSettings delegate:self];
}

- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhotoSampleBuffer:(nullable CMSampleBufferRef)photoSampleBuffer previewPhotoSampleBuffer:(nullable CMSampleBufferRef)previewPhotoSampleBuffer resolvedSettings:(AVCaptureResolvedPhotoSettings *)resolvedSettings bracketSettings:(nullable AVCaptureBracketedStillImageSettings *)bracketSettings error:(nullable NSError *)error
{
    NSData *data = [AVCapturePhotoOutput JPEGPhotoDataRepresentationForJPEGSampleBuffer:photoSampleBuffer previewPhotoSampleBuffer:previewPhotoSampleBuffer];
    UIImage *image = [UIImage imageWithData:data];
    [self.imgArray addObject:image];
    [self.scanningView setMImgPreviewImg:image num:(int)self.imgArray.count];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSMutableArray *)imgArray
{
    if (!_imgArray) {
        
        _imgArray = [[NSMutableArray alloc] init];
    }
    return _imgArray;
}
//// 移除定时器
//-(void)dealloc
//{
//    [self.scanningView removeTimer];
//}

@end
